package com.ltmonitor.web.controller.mobile;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.mobile.entity.UserGpsInfo;
import com.ltmonitor.mobile.entity.UserGpsRealData;
import com.ltmonitor.service.ILocationService;
import com.ltmonitor.service.IUserGpsInfoService;
import com.ltmonitor.service.IUserGpsRealDataService;
import com.ltmonitor.web.controller.GenericAction;
import com.ltmonitor.web.util.JsonMessage;

/**
 * 用户位置汇报
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/mobile")
public class UserLocationAction extends GenericAction {

	@Autowired
	private ILocationService locationService;
	@Autowired
	private IUserGpsRealDataService userGpsRealDataService;
	@Autowired
	private IUserGpsInfoService userGpsInfoService;

	@ResponseBody
	@RequestMapping("/upldateLocation.action")
	public JsonMessage execute(double longitude, double latitude, double velocity, int direction,Date sendTime,int userId,double accuracy) {
		try {
			String hql = "from UserGpsRealData where userId = ?";

			UserGpsRealData g = (UserGpsRealData) this.userGpsRealDataService.find(hql,
					userId);
			if (g == null) {
				g = new UserGpsRealData();
				g.setUserId(userId);
			}else if(g.getSendTime() != null && g.getSendTime().compareTo(sendTime) >= 0)
			{
				//重复定位数据，不再入库
				return json(true,"");
			}

			g.setLatitude(latitude);
			g.setLongitude(longitude);
			g.setAccuracy(accuracy);
			g.setSendTime(sendTime);
			String location = locationService.getLocation(latitude, longitude);
			g.setLocation(location);
			//保存到实时表
			this.userGpsRealDataService.saveOrUpdate(g);

			UserGpsInfo gi = new UserGpsInfo();
			gi.setLatitude(latitude);
			gi.setLongitude(longitude);
			gi.setSendTime(sendTime);
			gi.setVelocity(velocity);
			gi.setAccuracy(accuracy);
			gi.setDirection(direction);
			gi.setUserId(userId);
			gi.setLocation(g.getLocation());
			//保存到历史定位表中
			this.userGpsInfoService.save(gi);
		} catch (Exception ex) {
			log.error(ex.getMessage());
			log.error(ex.getStackTrace());
			return json(false, ex.getMessage());
		}

		return json(true, "");
	}

	@ResponseBody
	@RequestMapping("/getUserRealData.action")
	public JsonMessage getRealData(long userId) {
		try {
			String hql = "from UserGpsRealData where userId = ?";

			UserGpsRealData g = (UserGpsRealData) this.userGpsRealDataService.find(hql,
					userId);
			return json(true, g);
		} catch (Exception ex) {
			log.error(ex.getMessage());
			log.error(ex.getStackTrace());
			return json(false, ex.getMessage());
		}

	}


}
